<template>
  <div>
    <el-dialog
      :title="name"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      class="mt-dialog"
      width="80%"
      @close="close"
    >

      <div class="top">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-select v-model="item_type" size="mini" placeholder="模板类型" clearable style="width: 30%">
              <el-option value="" label="所有" />
              <el-option
                v-for="name in template_types"
                :key="name"
                :label="name"
                :value="name"
              />
            </el-select>
          </el-col>
          <el-col :span="12">
            <el-input
              v-model="kwInput"
              placeholder="输入 任意字符 进行筛选"
              class="input-with-select"
              clearable
              @keyup.native.enter="handleSearch"
            >
              <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            </el-input>
            <el-button
              type="primary"
              class="el-icon-plus add-btn"
              :disabled="listLoading"
              @click="handleAction('create', '添加')"
            >添加
            </el-button>
          </el-col>
        </el-row>

      </div>

      <el-table
        v-loading.fullscreen.lock="listLoading"
        :data="data"
        border
        fit
        highlight-current-row
        style="width: 100%"
        @cell-mouse-enter="(m) => m.active=true"
        @cell-mouse-leave="(m) => m.active=false"
        @sort-change="handleSort"
      >
        <el-table-column align="center" label="name" prop="name" sortable="custom" />
        <el-table-column align="center" label="type" prop="type" sortable="custom" />
        <el-table-column align="center" label="图库" prop="images">
          <template slot-scope="scope">
            <span @click="showRowImages(scope.row)">{{ scope.row.images !== ''? scope.row.images.split('|').length: 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="200">
          <template slot-scope="scope">
            <el-button size="mini" type="success" @click="handleAction('edit', scope.row)">修改</el-button>
            <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
          </template>
        </el-table-column>

      </el-table>

      <el-pagination
        v-if="data.length"
        background
        class="mt-pagination"
        :current-page="page"
        :page-sizes="[10,20,50,100]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
      <el-dialog
        append-to-body
        :title="image_dialog_title"
        style="height: 600px; overflow:auto"
        :visible.sync="imageDialogVisible"
        :close-on-click-modal="false"
      >
        <div class="demo-image__lazy">
          <el-image
            v-for="url in modify_images"
            :key="url"
            style="width: 100px; height: 100px; margin: 5px"
            fit="fill"
            :src="url"
            lazy
            @click="removeImage(url)"
          />
        </div>
        <el-input v-model="new_image_url" placeholder="添加新图片">
          <el-button slot="append" icon="el-icon-plus" @click="addNewImage" />
        </el-input>
        <span slot="footer" class="dialog-footer">
          <gallery color="#1890ff" class="editor-upload-btn" @successCBK="imageSuccessCBK" />
          <el-button @click="imageDialogVisible = false">取 消</el-button>
          <el-button type="danger" @click="handleSaveImages">保 存</el-button>
        </span>
      </el-dialog>

      <el-dialog
        append-to-body
        :title="title"
        :width="width"
        :visible.sync="innerDialogVisible"
        :close-on-click-modal="false"
      >
        <el-form :model="temp" label-position="left" label-width="80px">
          <el-form-item label="分组名称">
            <el-input v-model="temp.name" placeholder="同一类型分组名称必须唯一" />
          </el-form-item>
          <el-form-item label="模板类型">
            <el-select v-model="temp.type" size="mini" placeholder="模板类型" clearable>
              <el-option
                v-for="name in template_types"
                :key="name"
                :label="name"
                :value="name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="图库">
            <el-input v-model="temp.images" placeholder="图片链接，多个图片使用|分开" />
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="innerDialogVisible = false">取 消</el-button>
          <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
        </span>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/cms/blogtemplategroup'
import qs from 'qs'
import Gallery from '../../../components/Tinymce/components/gallery'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  name: 'Blogtemplategroup',
  components: { Gallery },
  props: ['webVisible', 'type', 'name'],
  data() {
    return {
      count: 0,
      image_dialog_title: '图库管理',
      imageDialogVisible: false,
      modify_row_id: '',
      modify_images: [],
      new_image_url: '',
      data: [],
      listLoading: false,
      kwInput: '',
      item_type: '',
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,

      action: null,
      dialogVisible: false,
      title: '',
      temp: {
        name: '',
        type: '',
        images: ''
      },
      template_types: ['post_template', 'amazon_product', 'intro_paragraph', 'product_middle_paragraph',
        'end_paragraph', 'title_template'
      ],
      width: '',
      innerDialogVisible: false
    }
  },
  watch: {
    webVisible(v) {
      this.dialogVisible = v
      this.item_type = this.type
      this.getList()
    }
  },
  methods: {
    imageSuccessCBK(arr) {
      arr.forEach(v => {
        for (let i = 0; i < this.modify_images.length; i++) {
          if (this.modify_images[i] === v.url) {
            return false
          }
        }
        this.modify_images.push(v.url)
      })
    },
    removeImage(url) {
      this.new_image_url = ''
      const index = this.modify_images.indexOf(url)
      if (index > -1) {
        this.modify_images.splice(index, 1)
      }
    },
    showRowImages(row) {
      this.modify_images = row.images ? row.images.split('|') : []
      this.modify_row_id = row.id
      this.image_dialog_title = row.name + '图片库管理'
      this.imageDialogVisible = true
    },
    addNewImage() {
      if (this.new_image_url === '') {
        return false
      }
      for (let i = 0; i < this.modify_images.length; i++) {
        if (this.modify_images[i] === this.new_image_url) {
          return false
        }
      }
      this.modify_images.push(this.new_image_url)
      this.new_image_url = ''
    },
    handleSaveImages() {
      Put(this.modify_row_id, { 'id': this.modify_row_id, 'images': this.modify_images.join('|') }
      ).then(response => {
        this.imageDialogVisible = false
        this.getList()
        this.notify('修改成功')
      })
    },
    handleShowLongTailKeyword(row) {
      this.longtail_mainkeyword_id = row.id
      this.longtailkeywordName = row.keyword + '长尾词'
      this.longtailKeywordVisible = true
    },
    resetTemp() {
      this.temp = {
        name: '',
        type: '',
        images: ''
      }
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        type: this.item_type,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.scrollTop()
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.width = '50%'
          this.title = '添加新分组'
          this.resetTemp()
          this.innerDialogVisible = true
          break
        case 'delete':
          this.width = '30%'
          this.title = `确认要删除${row.name}?`
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break
        case 'edit':
          this.width = '50%'
          this.title = `修改${row.name}`
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break
      }
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        case 'create':
          if (!_data.name.length) {
            alert('name is none')
            return
          }
          Post(this.temp
          ).then(response => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('添加成功')
          })
          break
        case
          'delete'
          :
          Delete(_data.id).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('删除成功')
          })
          break
        case
          'edit'
          :
          Put(_data.id, _data).then((response) => {
            this.innerDialogVisible = false
            this.$emit('reload')
            this.getList()
            this.notify('更新成功')
          })
          break
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    close() {
      this.$emit('closeDialog', false)
    }
  }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}

.top >>> .el-select .el-input {
  width: 350px;
}

.top >>> .input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.top {
  padding-left: 20px;
  margin-bottom: 30px;
  margin-top: 28px;
}

.input-with-select {
  width: calc(100% - 200px);
}

.add-btn {
  float: right;
  margin-right: 20px;
  width: 150px
}

.mt-pagination {
  float: right;
  margin-top: 5px;
}

.app-container >>> .el-dialog {
  margin-top: 48px !important;
  margin-bottom: 68px;
}

.mt-dialog >>> .el-transfer-panel {
  width: calc(50% - 60px);
}

.mt-form >>> .el-select {
  width: 100%;
}

.mt-form >>> .el-input__inner {
  width: 100%;
}

.mt-dialog >>> .el-dialog {
  margin-top: 60px;
  /*margin: 168px auto !important;*/
}

.mt-dialog >>> .el-dialog__body {
  padding-bottom: 100px;
}
</style>
